package com.legendframework.dao.transaction;

import com.legendframework.dao.transaction.pojo.ThreadData;

import java.sql.SQLException;

public class JdbcTransaction extends AbstractTransaction<ThreadData> {

    @Override
    public void start() {
        try {
            //设置为不自动提交
            getThreadLocalData().getConnection().setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void commit() {
        try {
            //手动提交
            getThreadLocalData().getConnection().commit();
            //恢复自动提交
            getThreadLocalData().getConnection().setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void back() {
        try {
            //回滚
            getThreadLocalData().getConnection().rollback();
            //恢复自动提交
            getThreadLocalData().getConnection().setAutoCommit(true);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 校验线程变量中的参数
     * @return
     */
    protected boolean check(){
        ThreadData threadLocal = getThreadLocalData();
        try {
            return threadLocal != null && threadLocal.getConnection() != null && threadLocal.getConnection().isValid(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
